package domain;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class OnePart {

	
	private static Pattern p = Pattern.compile(";(.+?)=\"(.+?)\""); 
	

	private Map<String, String> map_head = new HashMap<String, String>();
	
	// data
	private ByteArrayOutputStream baos = new ByteArrayOutputStream();
	
	/**
	 * 
	 * @param header
	 */
	public void addHeader(String header){
		// get mime
		if(header.indexOf("Content-Type:")!=-1){
			String mime = header.replace("Content-Type:", "").trim();
			map_head.put("mime", mime);
			return;
		}
		
		// get disposition
		Matcher m = p.matcher(header);
		while(m.find()){
			String key = m.group(1).trim();
			String value = m.group(2).trim();
			map_head.put(key, value);
		}
	}
	
	
	///////////////////////////	
	public String getName() {
		return map_head.get("name");
	}

	public String getValue() {
		try {
			return new String(getData(),"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}
	///////////////////////////
	
	
	// for binary data //
	public byte[] getData(){
		return baos.toByteArray();
	}
	public OnePart addData(byte[] b,int off,int len){
		baos.write(b, off, len);
		return this;
	}
	public OnePart addData(byte[] b) throws IOException{
		baos.write(b);
		return this;
	}
	public int getDataLength(){
		return baos.size();
	}
	///////////////////////////
	

	public String getFileName() {
		return map_head.get("filename");
	}

	public String getMime() {
		return map_head.get("mime");
	}



	public static void main(String[] args) {
		OnePart op = new OnePart();
		op.addHeader("Content-Disposition: form-data; name=\"data\"; filename=\"test.txt\"");
		op.addHeader("Content-Type: text/plain");
		
		
		System.out.println(op.getFileName());
		System.out.println(op.getMime());
		System.out.println(op.getName());
		
	}


	
	

	
	
	
	
	

	
	
	
}
